'use strict';

/**
 * @name DemandDetailEditCtrl
 * @author ZYF
 */

angular.module('metalabOperationApp').controller('DemandDetailEditCtrl', ['$scope', '$rootScope', '$state', '$stateParams', 'MetaResources', 'MetaRemind', 'MetaEdit', function($scope, $rootScope, $state, $stateParams, MetaResources, MetaRemind, MetaEdit) {
    $scope.editCtrl = {
        data: {}
    };
    $scope.init = function() {
        MetaEdit.initEditModule($scope, $stateParams, 'demand', 'publisher,leader,projectManager,other,verifier');
    };
    $scope.save = function() {
        MetaEdit.setPreProcess($scope.editCtrl.data, 'demand');
        var totalUpdateCount = 1;//总共需要更新需求的信息，以及负责人的信息
        var alreadyUpdatecount = 0;//已经更新好了的信息
        //如果负责人不为空，则更新其信息，并将需要更新的数量加1
        if ($scope.editCtrl.data.leaderId) {
          totalUpdateCount++;
            console.log($scope.editCtrl.data.leader);
          MetaResources.user.save({
                  'id': $scope.editCtrl.data.leaderId
              }, $scope.editCtrl.data.leader,
              function() {
                  update();
              },
              function(error) {
                  MetaRemind.serverError(error);
              });
        }
        //更新需求信息
        MetaResources.demand.save({
                'id': $stateParams.id,
                '_embed': 'publisher,leader,projectManager'
            }, $scope.editCtrl.data,
            function() {
                update();
            },
            function(error) {
                MetaRemind.serverError(error);
            });
        //判断是不是全部更新完成
        var update = function() {
            alreadyUpdatecount++;
            if (alreadyUpdatecount === totalUpdateCount) {
                MetaRemind.success("恭喜", "修改成功");
                MetaEdit.syncData($scope.editCtrl, 'demand');
            }
        };
    };

    $scope.toBeContinued = MetaRemind.error;
    $scope.init();
}]);
